<template>
  <div class="store-match-box">
    <table-index :table="form.customList">
      <template #table-summary>
        <a-alert v-if="query.sourceStatus != '3' && query.sourceId == '8'" class="mr-4">
          飞租不允许新增门店，如有需要请先在飞租创建门店，再【同步门店】即可。
        </a-alert>
      </template>
      <template #siteName="{ record, rowIndex }">
        <template v-if="record.id">
          {{ record.siteName }}
        </template>
        <page-form-item
          v-else
          size="1/2"
          style="margin-bottom: 0"
          :field="`customList.dataList.${rowIndex}.siteName`"
          :rules="{ required: true, message: '请输入' }"
          required
        >
          <i-input v-model="record.siteName" :max-length="20" />
        </page-form-item>
      </template>
      <template #relationSiteId="{ record, rowIndex }">
        <template v-if="record.status === 'create'">
          {{ record.relationSiteName }}
        </template>
        <page-form-item v-else style="margin-bottom: 0" size="1/2">
          <remote-select
            style="width: 100%"
            v-model="record.relationSiteId"
            :index="rowIndex"
            type="site_lease_list_2"
            @change="onStoreChange"
            :popupContainer="'.page-container'"
            :updateAtScroll="true"
            :scrollToClose="true"
          />
        </page-form-item>
      </template>
    </table-index>
  </div>
</template>

<script setup lang="ts">
  import { ref, inject, onMounted } from 'vue'
  import { getChannelStoreList, saveChannelStore, syncAccount, deleteChannelStore, syncAccountInfoStatus } from '@/api/business/ota'
  import getFuncOnLoopCondition from '@/utils/getFuncOnLoopCondition'
  import { useTable } from '@/hooks/table'
  import { Message } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'

  const route = useRoute()
  const { params, query } = route
  console.log(route, 'store-match')

  const props = defineProps({
    accountId: String,
  })

  const form = ref(inject<any>('form'))
  const formRef = inject<any>('formRef')
  form.value.customList = useTable({
    tableLoading: false,
    pagination: false,
    columns: [
      {
        title: 'OTA渠道门店',
        dataIndex: 'siteName',
        key: 'siteName',
        slotName: 'siteName',
      },
      {
        title: '商户门店',
        dataIndex: 'relationSiteId',
        key: 'relationSiteId',
        slotName: 'relationSiteId',
      },
    ],
    operates: [
      {
        label: '修改',
        show: (record: any) => record.id && record.status === 'create',
        method: (record: any, column: any, rowIndex: number) => {
          console.log(record, column, rowIndex)
          record.status = 'edit'
        },
      },
      {
        label: '保存',
        show: (record: any) => record.status === 'edit',
        method: (record: any, column: any, rowIndex: number) => {
          console.log(record, column, rowIndex)
          onSaveStoreMatch(record)
        },
      },
      {
        label: '删除',
        method: (record: any, column: any, rowIndex: number) => {
          formRef.value.clearValidate()
          if (record.id) {
            deleteChannelStore({ id: record.id }).then((res: any) => {
              console.log(res, '删除门店 deleteChannelStore')
              form.value.customList.dataList.splice(rowIndex, 1)
              loadData()
            })
          } else {
            form.value.customList.dataList.splice(rowIndex, 1)
          }
        },
      },
    ],
    buttons: [
      {
        // permission: 'svms:asstes:car:car-model:add',
        label: '同步门店',
        show: () => params.id && query.sourceStatus != '3',
        method: () => {
          Message.info('同步中，请稍后')
          onSyncStoreMatch()
        },
      },
      {
        type: 'primary',
        // permission: 'svms:asstes:car:car-model:add',
        show: () => params.id && query.sourceId != '8',
        icon: 'plus',
        label: '新增',
        method: () => {
          formRef.value.clearValidate()
          onAddStoreMatch()
        },
      },
    ],
    dataList: [],
  })

  const onAddStoreMatch = () => {
    form.value.customList.dataList.unshift({
      siteName: '',
      relationSiteId: '',
      accountId: params.id || props.accountId,
    })
  }

  const onStoreChange = (value: any, option: any, index: number) => {
    console.log(value, option, index, 'onStoreChange')
    form.value.customList.dataList[index].relationSiteName = option.siteName
  }

  // 保存门店
  const onSaveStoreMatch = (record: any) => {
    console.log('保存门店', record)
    saveChannelStore(record).then((res: any) => {
      console.log(res, '保存门店 saveChannelStore')
      record.status = 'create'
      // loadData()
    })
  }

  // 检查同步账号信息状态
  const checkSyncAccountCondition = (response: any) => {
    return response.result === 0
  }

  // 同步门店
  const onSyncStoreMatch = () => {
    syncAccount({ id: params.id || props.accountId }).then((res: any) => {
      console.log(res, '同步门店 syncAccountStore')
      // Message.success('同步成功')
      const executor = async () => {
        const response = await syncAccountInfoStatus({ id: params.id || props.accountId })
        return response
      }
      const condition = checkSyncAccountCondition
      const delay = 1000
      getFuncOnLoopCondition(executor, condition, delay)
        .then(() => {
          loadData()
        })
        .catch((error: any) => {
          console.log(error, '同步门店 error')
        })
    })
  }

  let copyCustomList = ref()
  const loadData = () => {
    getChannelStoreList({ accountId: params.id || props.accountId }).then((res: any) => {
      res.result.forEach((item: any) => {
        item.status = 'create'
      })
      copyCustomList.value = JSON.stringify(res.result)
      form.value.customList.dataList = res.result
    })
  }

  onMounted(() => {
    loadData()
  })

  defineExpose({
    loadData,
    copyCustomList,
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table .arco-table-td .arco-table-cell) {
    padding-top: 14px;
    padding-bottom: 14px;
  }
  .store-match-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    &__empty {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .arco-icon-empty {
        margin-bottom: 4px;
        color: rgba(216, 216, 216, 1);
      }

      span {
        font-size: 12px;
        font-weight: 400;
        margin-bottom: 8px;
        color: rgba(216, 216, 216, 1);
      }
    }

    .btn-list {
      position: absolute;
      right: -190px;
      width: 190px;
      padding-left: 29px;
      .btn-item {
        font-size: 14px;
        height: 32px;
        line-height: 32px;
        white-space: nowrap;
        outline: none;
        cursor: pointer;
        user-select: none;
        padding: 0 5px;
        icon {
          margin-right: 8px;
        }
        &.del {
          color: #ea0000;
        }
        &.new {
          color: #165dff;
        }
      }
    }
  }
</style>
